<?php
namespace Pumpeddevs\TheNewBasics\BookTitleList;

defined('ABSPATH') or die("Page not found");

use Pumpeddevs\Library\Plugin;
use Pumpeddevs\Library\Session;
use Pumpeddevs\TheNewBasics\Model\BookExcerpt;

/**
 * Description of BookTitleList
 *
 * @author Pumpeddevs <pumpeddevs@gmail.com>
 */

class BookTitleListController extends Plugin{

	protected function init() {
		$this->setViewPath(__DIR__ . '/views');
		add_action('wp_ajax_nopriv_booktitle',array(&$this,'booktitle'));
		add_action('wp_ajax_nopriv_searchbook',array(&$this,'searchbook'));
		add_action('wp_ajax_nopriv_loadtenbook',array(&$this,'loadtenbook'));
		add_action('wp_ajax_loadtenbook',array(&$this,'loadtenbook'));
		add_action('wp_ajax_nopriv_loadtenchildbook',array(&$this,'loadtenchildbook'));
		add_action('wp_ajax_loadtenchildbook',array(&$this,'loadtenchildbook'));
	}

	protected function setup() {
		
	}

	public function loadCss() {
		
	}

	public function loadJS() {
		
	}

	public function booktitle() {
		$post = get_post($_GET['p']);
		die($this->render('viewbookcontentajax',
			array('title'=>$post->post_title,'content'=>$post->post_content)));
	}

	public function searchbook() {

	}

	public function loadtenchildbook() {
		global $wpdb;
		if(Session::getInstance()->isExist('userid')) {
			$maxtitle = get_option('maxtitle', 30);
			$p = sanitize_text_field($_GET['p']);
			$childbooks = BookExcerpt::getInstance()->getChildBookTitle($maxtitle,$p);
			$titles = array();
			$cntr = 0;
			foreach($childbooks as $childbook) {
				$titles[$cntr]['title'] = $childbook->book_title;
				$titles[$cntr]['link'] = get_permalink($childbook->ID);
				$titles[$cntr]['id'] = $childbook->ID;
				$cntr++;
			}
			die(json_encode($titles));
		}
	}

	public function loadtenbook() {
		global $wpdb;
		$maxtitle = get_option('maxtitle', 30);
		$p = sanitize_text_field($_GET['p']);
		$data = BookExcerpt::getInstance()->getBookTitle($maxtitle,$p);		
		$titles = array();
		$cntr = 0;
		while($data->have_posts()) : $data->the_post();
			$titles[$cntr]['title']	= the_title('','',false);
			$titles[$cntr]['link'] = get_permalink();
			$titles[$cntr]['id'] = get_the_ID();
			$cntr++;
		endwhile;
		die(json_encode($titles));
	}

}
